package com.chexiehui.jc.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.TextView;

import com.aries.ui.widget.alert.UIAlertDialog;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.adapter.SeriesBannerAdapter;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.ShopInfo;
import com.chexiehui.jc.entity.SpecialCarInfo;
import com.chexiehui.jc.mvp.car.ShopDetailsCovenant;
import com.chexiehui.jc.mvp.car.ShopDetailsPresenter;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.FixedSpeedScroller;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.widget.CustomXPopupImageLoader;
import com.chexiehui.jc.widget.LoadingLayout;
import com.lxj.xpopup.XPopup;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.tmall.ultraviewpager.UltraViewPager;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 店铺详情
 */
public class ShopDetailsActivity extends BaseMvpActivity<ShopDetailsPresenter> implements ShopDetailsCovenant.View {

    @BindView(R.id.ultra_banner)
    UltraViewPager ultraViewPager;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_shop_introduce)
    TextView tvShopIntroduce;
    @BindView(R.id.tv_shop_address)
    TextView tvShopAddress;
    @BindView(R.id.tv_shop_phone)
    TextView tvShopPhone;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    private String shopId;
    private ShopInfo shopInfo;
    private CommonAdapter<SpecialCarInfo> specialCarAdapter;
    private BasePage<SpecialCarInfo> page;

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            shopId = bundle.getString("id");
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String id = bundle.getString("id");
             if(!StringUtils.isTrimEmpty(id) && getShopId().equals(id)){
                 return;
             }
            shopId = id;
        }else{
            return;
        }
        if(StringUtils.isTrimEmpty(getShopId())){
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText("暂无4S店详情");
            return;
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getShopInfo();
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("4S店详情");
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_shop_details;
    }

    @Override
    protected void initView(Bundle var1) {
        if(StringUtils.isTrimEmpty(getShopId())){
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText("暂无4S店详情");
            return;
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        loadingLayout.setOnReloadListener(v -> {
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getShopInfo();
        });
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(false);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mvpPresenter.getShopInfo();
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (page != null && page.getTotalRecordCount() > specialCarAdapter.getDatas().size()) {
                    mvpPresenter.getCarList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });
        recycler.setLayoutManager(new LinearLayoutManager(mContext));
        specialCarAdapter = new CommonAdapter<SpecialCarInfo>(mContext, R.layout.item_special_car_simple, new ArrayList<>()) {
            @Override
            protected void convert(ViewHolder holder, SpecialCarInfo item, int position) {
                holder.setText(R.id.tv_item_name, item.getName());
                holder.setText(R.id.tv_item_price, item.getSpecialPriceStr());
                holder.setText(R.id.tv_item_old_price, item.getNewPriceStr());
            }
        };
        recycler.setAdapter(specialCarAdapter);
        specialCarAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                startActivity(SpecialCarDetailsActivity.class, new BundleBuilder().putString("id", specialCarAdapter.getDatas().get(position).getId()).create());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mvpPresenter.getShopInfo();
    }

    private void setShopInfo() {
        tvShopName.setText(shopInfo.getName());
        tvShopAddress.setText(shopInfo.getAdress());
        tvShopIntroduce.setText(shopInfo.getStoreIntroduce());
        tvShopPhone.setText(shopInfo.getTel());
        if (shopInfo.getImgs().size() > 0) {
            ultraViewPager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
            try {
                Field mField;
                mField = ViewPager.class.getDeclaredField("mScroller");
                mField.setAccessible(true);
                FixedSpeedScroller mScroller =
                        new FixedSpeedScroller(mContext, new AccelerateInterpolator());
                mScroller.setmDuration(1000);
                mField.set(ultraViewPager.getViewPager(), mScroller);
            } catch (Exception e) {
            }
            ultraViewPager.setAutoMeasureHeight(false);
            SeriesBannerAdapter seriesBannerAdapter = new SeriesBannerAdapter(shopInfo.getImgs(), (url, isVideo) -> {
                if (isVideo) {
                    VideoPlayActivity.start(ShopDetailsActivity.this, shopInfo.getName(), url);
                } else {
                    try {
                        new XPopup.Builder(mContext)
                                .asImageViewer(null, url, new CustomXPopupImageLoader())
                                .show();
                    } catch (Exception e) {
                    }
                }
            });
            ultraViewPager.setAdapter(seriesBannerAdapter);
            //内置indicator初始化
            ultraViewPager.initIndicator();
            //设置indicator样式
            ultraViewPager.getIndicator()
                    .setOrientation(UltraViewPager.Orientation.HORIZONTAL)
                    .setFocusColor(ContextCompat.getColor(mContext, R.color.colorWhite))
                    .setNormalColor(ContextCompat.getColor(mContext, R.color.c_999999))
                    .setRadius(SizeUtils.dp2px(4));
            //设置indicator对齐方式
            ultraViewPager.getIndicator().setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
            ultraViewPager.getIndicator().setMargin(0, 0, 0, SizeUtils.dp2px(10));
            //构造indicator,绑定到UltraViewPager
            ultraViewPager.getIndicator().build();
            //设定页面循环播放
            ultraViewPager.setInfiniteLoop(true);
            //设定页面自动切换  间隔5秒
            ultraViewPager.setAutoScroll(5000);
        }
    }

    @Override
    protected ShopDetailsPresenter createPresenter() {
        return new ShopDetailsPresenter(this);
    }

    @Override
    public void onGetShopInfoSuccess(BaseModel<ShopInfo> successResult) {
        loadingLayout.setStatus(LoadingLayout.Success);
        shopInfo = successResult.getData();
        setShopInfo();
        mvpPresenter.getCarList(1);
    }

    @Override
    public void onGetShopInfoFailure(BaseModel<Object> failureResult) {
        if (failureResult.getResultCode() == Constants.PAGE_DATA_EMPTY) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText(failureResult.getResultInfo());
        } else {
            loadingLayout.setStatus(LoadingLayout.Error);
            loadingLayout.setErrorText(failureResult.getResultInfo());
        }
    }

    @Override
    public void onGetCarListSuccess(BaseModel<BasePage<SpecialCarInfo>> successResult) {
        page = successResult.getData();
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            specialCarAdapter.getDatas().clear();
            specialCarAdapter.getDatas().addAll(page.getItems());
            specialCarAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            specialCarAdapter.getDatas().addAll(page.getItems());
            specialCarAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= specialCarAdapter.getDatas().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            specialCarAdapter.getDatas().clear();
            specialCarAdapter.getDatas().addAll(page.getItems());
            specialCarAdapter.notifyDataSetChanged();
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh(true);
        }
    }

    @Override
    public void onGetCarListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (specialCarAdapter.getDatas().size() > 0) {
                    specialCarAdapter.getDatas().clear();
                    specialCarAdapter.notifyDataSetChanged();
                }
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
            showToast(failureResult.getResultInfo());
        }
    }

    @Override
    public String getShopId() {
        return shopId == null ? "" : shopId;
    }

    private void callPhone() {
        AndPermission.with(this)
                .permission(Permission.PHONE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        PhoneUtils.call(shopInfo.getTel());
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_LOACTION).show();
                        } else {
                            showToast(getStringSource(R.string.app_name) + "需要您授权电话权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_CARAME)
                .rationale((requestCode, rationale) -> AndPermission.rationaleDialog(mContext, rationale).show()).start();
    }

    @OnClick({R.id.tv_shop_address, R.id.tv_shop_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_shop_address:
                startActivity(MapLocationActivity.class, new BundleBuilder()
                        .putDouble("latitude", shopInfo.getLat())
                        .putDouble("longitude", shopInfo.getLon())
                        .putFloat("mapLeave", 15.f)
                        .putString("street", shopInfo.getAdress())
                        .create());
                break;
            case R.id.tv_shop_phone:
                if (StringUtils.isTrimEmpty(shopInfo.getTel())) {
                    showToast("暂无电话信息");
                    return;
                }
                UIAlertDialog dialog = new UIAlertDialog.DividerIOSBuilder(mContext)
                        .setTitle("拨打电话")
                        .setMessage(shopInfo.getTel())
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).setPositiveButton("拨打", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                callPhone();
                                dialog.dismiss();
                            }
                        }).create();
                dialog.show();
                break;
        }
    }
}
